package common

import (
	"gorm.io/gorm"
	"gvb_server/global"
	"gvb_server/models"
)

func Page[T any](model T, page models.Page) (list []T, count int64) {
	// 是否打印sql日志
	DB := global.DB
	if global.Config.Mysql.PrintSql {
		DB = global.DB.Session(&gorm.Session{Logger: global.MysqlLog})
	}
	// 处理分页、排序信息(默认降序)
	if page.Page <= 0 {
		page.Page = 1
	}
	if page.Limit <= 0 || page.Limit > 100 {
		page.Limit = 10
	}
	offset := (page.Page - 1) * page.Limit
	if offset < 0 {
		offset = 0
	}
	if page.Sort == "" {
		page.Sort = "created_at desc"
	}
	// 通用的分页查询
	DB.Model(model).Select("id").Count(&count)
	DB.Limit(page.Limit).Offset(offset).Order(page.Sort).Find(&list)
	return list, count
}
